package com.wk.controller;

import com.wk.temp.UserOld;
import com.wk.myannotation.DoneTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Controller
public class UserOldController {

    @Autowired
    private MessageSource ms;

    @PostMapping(value = "/Valid")
    public Map<String,String> index(@Valid UserOld userOld, BindingResult bindingResult)
    {
        Map<String,String>  map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        if(bindingResult.hasErrors())
        {
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError error:list)
            {
                sb.append(error.getDefaultMessage());
                sb.append("----");
            }
            map.put("error",sb.toString());
            map.put("user", userOld.toString());
        }

        return map;
    }

    @GetMapping("/")
    @DoneTime(param = "has work?")
    public String index(Model model){
        Locale locale = LocaleContextHolder.getLocale();
        model.addAttribute("message",ms.getMessage("message",new String[]{"Java","WANGKUN"},locale));
        return "index";
    }

    @GetMapping(value = "/test")
    public String testError() {
        String na = null;
        return na.toString();
    }

}
